<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入设备名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-240px" clearable placeholder="请选择状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FACILITY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仪器类型" prop="instrumentType">
        <el-select v-model="queryParams.instrumentType" class="!w-240px"   placeholder="请选择仪器类型" @change="onInstrumentTypeChange">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.INSTRUMENT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          class="!w-240px"
          clearable
          placeholder="请输入型号"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button

          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button

          :loading="exportLoading"
          plain
          type="success"
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :show-overflow-tooltip="true"
      :stripe="true"
      @selection-change="handleSelectionChange"
      @row-dblclick="(row) => handleSelectionChange([row])"
    >
      <el-table-column align="center" label="序号" type="index" width="80" />
      <el-table-column v-if="showSelection" align="center" type="selection" width="55" />
      <el-table-column align="center" label="设备名称" prop="name" />
      <el-table-column align="center" label="编号" prop="serialNumber" />
      <el-table-column align="center" label="型号" prop="model" />
      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FACILITY_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="仪器类型" prop="instrumentType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INSTRUMENT_TYPE" :value="scope.row.instrumentType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="120px">
        <template #default="scope">
          <el-button

            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button

            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <FacilityForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import { FacilityApi, FacilityVO } from '@/api/infra/facility'
import FacilityForm from './FacilityForm.vue'

/** 设备管理 列表 */
defineOptions({ name: 'Facility' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<FacilityVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  name: undefined,
  serialNumber: undefined,
  status: undefined,
  model: undefined,
  calibrator: undefined,
  standardValue: undefined,
  finalCalibrationTime: [],
  manufacturer: undefined,
  instrumentType: undefined,
  note: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const props = defineProps({
  showSelection: {
    type: Boolean,
    default: false
  },
  defaultStatus: {
    type: Number,
    default: undefined
  } ,
  instrumentType: {
    type: String,
    default: undefined
  }
})

const emit = defineEmits(['select', 'selection-change', 'handle-facility-confirm'])

const handleSelectionChange = (selection: any[]) => {
  if (!props.showSelection) {
    selection = [selection]
  }
  emit('selection-change', selection)
  emit('handle-facility-confirm')
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FacilityApi.getFacilityPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 仪器类型选择变更，立即刷新列表
const onInstrumentTypeChange = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.status = props.defaultStatus // 重置后保持默认状态值
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FacilityApi.deleteFacility(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await FacilityApi.exportFacility(queryParams)
    download.excel(data, '设备管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  // 如果有默认状态值，设置查询条件
  if (props.defaultStatus !== undefined) {
    queryParams.status = props.defaultStatus
  }
  // 使用传入的 instrumentType 初始化下拉条件，但不直接传给接口
  if (props.instrumentType !== undefined) {
    queryParams.instrumentType = props.instrumentType as any
  }
  getList()
})

// 当外部变更 instrumentType 时，同步到查询条件
watch(
  () => props.instrumentType,
  (val) => {
    queryParams.instrumentType = val as any
    // 来自父组件的类型切换也需要立即刷新
    queryParams.pageNo = 1
    getList()
  }
)

// 下拉中“仪器类型”改变时，立即刷新列表

</script>
